package com.atguigu.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.atguigu.utils.JDBCUntils;

public abstract class BaseDaoimpl<T> {
	private QueryRunner qr;
	private Class<T> clazz; 
	public BaseDaoimpl() {
		qr = new QueryRunner();
		Type type = this.getClass().getGenericSuperclass();
		ParameterizedType pt = (ParameterizedType) type;
		Type type2 = pt.getActualTypeArguments()[0];
		clazz =  (Class<T>) type2;
		//System.out.println(clazz);
	}
	/**查询多个
	 * @param
	 * @param
	 * @return 如果为空，则操作失败，不为空，则成功
	 * */
	public List<T> getList(String sql, Object ... params){
		Connection conn = JDBCUntils.getConn();
		try {
			return qr.query(conn, sql, new BeanListHandler<T>(clazz) ,params);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		//return null;
	}
	
	/**查询单一操作
	 * @param
	 * @param 
	 * @return 如果为空，则操作失败，不为空，则成功
	 * */
	public T getOne(String sql,Object ...params) {
		Connection conn = JDBCUntils.getConn();
		try {
			return qr.query(conn, sql, new BeanHandler<T>(clazz), params);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	//	return null;
	}
	
	
	/**增删改操作
	 * @param sql
	 * @param params SQL语句中占位符参数
	 * @return 如果为零表示操作失败，否则返回正确的操作行
	 * */
	public int update(String sql,Object ...params) {
		Connection conn = JDBCUntils.getConn();
		try {
			return qr.update(conn, sql, params);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		//return 0;
	}
	/**获取总条数
	 * @param sql
	 * @param params
	 * */
	public Object getCount(String sql,Object...params) {
		Connection conn = JDBCUntils.getConn();
		try {
			return qr.query(conn, sql, new ScalarHandler(),params);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		//return null;
	}
	
}
